package biz.yfsoft.app.fastframework.plugin.icbc;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SignatureException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import biz.yfsoft.app.fastframework.kit.DateKit;
import biz.yfsoft.app.fastframework.kit.HttpsPost;
import cn.com.infosec.icbc.ReturnValue;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;

/**
 * 工行的信用支付接口
 * @author Frank
 *
 */
public class IcbcPay {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	/**
	 * 申请退款
	 */
	public static final String APPLY_REFUND = "0";
	
	/**
	 * 撤销退款
	 */
	public static final String REJECT_REFUND = "1";
	
	/**
	 * 确认退款
	 */
	public static final String COMMIT_REFUND = "2";

	private static IcbcPay _me;
	
	//在银行接口端设置的商户代码
	private String merID = "1103EC13759210";
	
	//支付之后的回调地址
	private String merURL = "http://fast.yfsoft.info/fastframework/admin/notify/payNotify";
	
	//商城账号
	private String merAcctNum = "1103020209200500343";
	
	//商城账户名称
	private String merAcctName = "煤炭";
	
	//非API接口地址
	private static final String NOAPI_URL= "https://{0}/servlet/ICBCINBSCreditPayCustReqServlet";
	
	//API接口地址
	private static final String API_URL= "https://{0}/servlet/ICBCINBSCreditPayReqServlet";
	
	//接口的域名
	private String domain = "corporbank.icbc.com.cn";
	
	private String merHint = "平台提示";
	
	//调试模式
	private String mode = "DEBUG";
	
	private boolean debug = false;
	
	private String date = null;
	
	/**
	 * 到期时间
	 */
	private String orderPeriod = "24";
	
	public static void config(final byte[] bcert,final byte[] bkey,JSONObject configJson){
		_me = new IcbcPay();
		String pass =  configJson.containsKey("password")?configJson.getString("password"):"123456";
		_me.keyPass = pass.toCharArray();
		_me.bcert = bcert;
		_me.bkey = bkey;
		byte[] EncCert = ReturnValue.base64enc(bcert);
		_me.merCert = new String(EncCert).toString();
		_me.configJson = configJson;
		if(configJson.containsKey("merID"))
			_me.merID = configJson.getString("merID");
		if(configJson.containsKey("merURL"))
			_me.merURL = configJson.getString("merURL");
		if(configJson.containsKey("merAcctNum"))
			_me.merAcctNum = configJson.getString("merAcctNum");
		if(configJson.containsKey("merAcctName"))
			_me.merAcctName = configJson.getString("merAcctName");
//		if(configJson.containsKey("postUrl"))
//			_me.postUrl = configJson.getString("postUrl");
		if(configJson.containsKey("mode"))
			_me.mode = configJson.getString("mode");
		if(configJson.containsKey("date"))
			_me.date = configJson.getString("date");
		if(configJson.containsKey("merHint"))
			_me.merHint = configJson.getString("merHint");
		if(configJson.containsKey("orderPeriod"))
			_me.orderPeriod = configJson.getString("orderPeriod");
		if(configJson.containsKey("domain"))
			_me.domain = configJson.getString("domain");
		_me.debug = "DEBUG".equalsIgnoreCase(_me.mode);
	}
	
	public static IcbcPay me(){
		if(_me == null){
			//插件未启动
			//TODO..给予错误警告
		}
		return _me;
	}
	
	private IcbcPay(){}
	
	@SuppressWarnings("unused")
	private byte[] bcert,bkey;
	
	private String merCert;
	
	private char[] keyPass;
	
	private JSONObject configJson;
	
	public JSONObject getConfig(){
		return this.configJson;
	}
	
	public String getCertBase64(){
		return merCert;
	}
	
	public String base64enc(String tranData){
		byte[] byteSrc = null;
		try {
			byteSrc = tranData.getBytes("GBK");
		} catch (UnsupportedEncodingException e1) {
		}
		try {
			byte[] sign =ReturnValue.sign(byteSrc,byteSrc.length,bkey,keyPass);
			byte[] EncSign = ReturnValue.base64enc(sign);
		    String SignMsgBase64 = new String(EncSign).toString();
		    return SignMsgBase64;
		} catch (InvalidKeyException | NoSuchProviderException
				| NoSuchAlgorithmException | SignatureException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public byte[] base64dec(byte[] src){
		//byte[] DecSign = ReturnValue.base64dec(EncSign);
		return null;
	}
	
	public String verifySign(String enc){
		
		return null;
	}
	
	/**
	 * 获取当前的交易时间，格式固定为 ： YYYYMMddHHmmss 14位
	 * @return
	 */
	public String getNowTranTime(){
		//如果是测试系统，则需要进行时间字段的调整
		String merTranTime = null;
		if(this.date == null){
			//没有使用配置的时间偏移
			merTranTime = DateKit.toStr(new Date(),"YYYYMMddHHmmss");
		}else{
			merTranTime = this.date + DateKit.toStr(new Date(),"HHmmss");
		}
		return merTranTime;
	}
	
	/**
	 * 解冻资金
	 */
	public void aheadPay(Controller ctrl,String orderId,String payTime){
		
		String merTranTime = getNowTranTime();
		
		String BASE_SIGNSTR = "interfaceName=ICBC_CORPORBANK_CREDIT_AHEAD_PAY&interfaceVersion=1.0.0.2"
				+ "&orderID={0}"   //订单号
				+ "&merOrderTime={1}"
				+ "&merTranTime={2}"
				+ "&feeAmt=0"
				+ "&merID={3}";//支付回调地址
		String merSignMsg = MessageFormat.format(BASE_SIGNSTR,
				orderId,
				payTime,
				merTranTime,
				merID
				);
		merSignMsg = base64enc(merSignMsg);
		StringBuffer buf = new StringBuffer();
		buf.append("<?xml  version=\"1.0\" encoding=\"GBK\" ?>"
					+ "<icbc_corporbank_credit_pay>"
						+ "<interfaceName>ICBC_CORPORBANK_CREDIT_AHEAD_PAY</interfaceName>"
						+ "<interfaceVersion>1.0.0.2</interfaceVersion>"
						+ "<order>"
							+ "<orderID>" + orderId + "</orderID>"
							+ "<merOrderTime>" + payTime + "</merOrderTime>"
							+ "<merTranTime>" + merTranTime + "</merTranTime>"
							+ "<feeAmt>0</feeAmt>"
						+ "</order>"
						+ "<merchant>"
							+ "<merID>" + merID + "</merID>"
						+ "</merchant>"
						+ "<security>"
							+ "<merSignMsg>" + merSignMsg + "</merSignMsg>"
							+ "<merCert>" + this.merCert + "</merCert>"
						+ "</security>"
					+ "</icbc_corporbank_credit_pay>");
		
		String xmlStr = buf.toString();
		buf = new StringBuffer();
		buf.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=GBK\"></head><body>")
		.append("<form id=\"form1\" action=\"").append(MessageFormat.format(NOAPI_URL, this.domain)).append("\" method=\"post\">")
		.append("<input type=\"hidden\" name=\"CREDIT_PAY_DATA\" value='"+xmlStr+"' />")
		.append("<input type=\"submit\"/>");
		ctrl.setAttr("formStr", buf.toString());
		ctrl.render("/pay.jsp");
	}
	/**
	 * 申请订单支付
	 * @param ctrl
	 * @param order
	 */
	public void pay(Controller ctrl,Map<String,Object> order){
		
		Object sellerAcct = (debug?merAcctNum:order.get("sellerAcct"));//收款账号，调试模式下会打款给商城
		Object sellerName = (debug?merAcctName:order.get("sellerName"));//收款单位名称，调试模式下会打款给商城
		
		String merTranTime = order.get("payTime").toString();
		
		String BASE_SIGNSTR = "interfaceName=ICBC_CORPORBANK_CREDIT_PREPARE_PAY&interfaceVersion=1.0.0.2"
				+ "&orderID={0}"   //订单号
				+ "&amount={1}&currType=001" //订单总额
				+ "&merTranTime={2}&orderPeriod={10}" //交易时间
				+ "&transMode=0" //到账模式
				+ "&feeAmt=0"
				+ "&subtFlag=1"
				+ "&sellerAcct={3}"//卖方账户
				+ "&sellerName={4}"//卖方名称
				+ "&merID={5}"//商户代码
				+ "&merAcctNum={6}"//商户手续费入账账号
				+ "&merAcctName={7}&verifyJoinFlag=2"//手续费入账账户户名
				+ "&merHint={8}"
				+ "&merURL={9}";//支付回调地址
		
		String merSignMsg = MessageFormat.format(BASE_SIGNSTR,
				order.get("id"),
				order.get("amount"),
				merTranTime,
				sellerAcct,
				sellerName,
				merID,
				merAcctNum,
				merAcctName,
				merHint,
				merURL,
				orderPeriod
				);
		logger.info("merSignMsg："+merSignMsg);
		merSignMsg = base64enc(merSignMsg);
		StringBuffer buf = new StringBuffer();
		buf.append("<?xml  version=\"1.0\" encoding=\"GBK\" standalone=\"no\" ?>"
					+ "<icbc_corporbank_credit_pay>"
						+ "<interfaceName>ICBC_CORPORBANK_CREDIT_PREPARE_PAY</interfaceName>"
						+ "<interfaceVersion>1.0.0.2</interfaceVersion>"
						+ "<order>"
							+ "<orderID>" + order.get("id") + "</orderID>"
							+ "<amount>" + order.get("amount") + "</amount>"
							+ "<currType>001</currType>"
							+ "<merTranTime>" + merTranTime + "</merTranTime>"
							+ "<orderPeriod>" + orderPeriod + "</orderPeriod>"
							+ "<transMode>0</transMode>"
					        + "<feeAmt>0</feeAmt>"
							+ "<subtFlag>1</subtFlag>"
						+ "</order>"
						+ "<seller>"
							+ "<sellerAcct>" + sellerAcct + "</sellerAcct>"
							+ "<sellerName>" + sellerName + "</sellerName>"
						+ "</seller>"
						+ "<merchant>"
							+ "<merID>" + merID + "</merID>"
							+ "<merAcctNum>" + merAcctNum + "</merAcctNum>"
							+ "<merAcctName>" + merAcctName + "</merAcctName>"
							+ "<verifyJoinFlag>2</verifyJoinFlag>"
						+ "</merchant>"
						+ "<message>"
							+ "<carriageAmt></carriageAmt>"
							+ "<goodsName></goodsName>"
							+ "<goodsNo></goodsNo>"
							+ "<goodsNum></goodsNum>"
							+ "<merHint>" + merHint + "</merHint>"
						+ "</message>"
						+ "<notify>"
							+ "<buyerPhoneNum></buyerPhoneNum>"
							+ "<sellerPhoneNum></sellerPhoneNum>"
							+ "<merURL>" + merURL + "</merURL>"
						+ "</notify>"
						+ "<security>"
							+ "<merSignMsg>" + merSignMsg + "</merSignMsg>"
							+ "<merCert>" + this.merCert + "</merCert>"
						+ "</security>"
					+ "</icbc_corporbank_credit_pay>");
		
		String xmlStr = buf.toString();
		buf = new StringBuffer();
		buf.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=GBK\"></head><body>")
		.append("<form id=\"form1\" action=\"").append(MessageFormat.format(NOAPI_URL, this.domain)).append("\" method=\"post\">")
		.append("<input type=\"hidden\" name=\"CREDIT_PAY_DATA\" value='"+xmlStr+"' />")
		.append("<input type=\"submit\"/></form></body></html>");
		ctrl.setAttr("formStr", buf.toString());
		ctrl.render("/pay.jsp");
	}
	
	
	public String refund(String orderId,String payTime,String refundType,Map<String,Object> refund){
		String merTranTime = getNowTranTime();
		
		String BASE_SIGNSTR = "interfaceName=ICBC_CORPORBANK_CREDIT_MODIFY&interfaceVersion=1.0.0.2"
				+ "&orderID={0}"   //订单号
				+ "&merOrderTime={1}"
				+ "&merTranTime={2}"
				+ "&merID={3}"
				+ "&refundAction={4}"
				+ "&refundAmt={5}"
				+ "&refundActionMsg={6}";
		String merSignMsg = MessageFormat.format(BASE_SIGNSTR,
				orderId,
				payTime,
				merTranTime,
				merID,
				refundType,
				refund.get("amount"),
				refund.get("msg")
				);
		merSignMsg = base64enc(merSignMsg);
		StringBuffer buf = new StringBuffer();
		buf.append("<?xml  version=\"1.0\" encoding=\"GBK\" ?>"
					+ "<icbc_corporbank_credit_pay>"
						+ "<interfaceName>ICBC_CORPORBANK_CREDIT_MODIFY</interfaceName>"
						+ "<interfaceVersion>1.0.0.2</interfaceVersion>"
						+ "<order>"
							+ "<orderID>" + orderId + "</orderID>"
							+ "<merOrderTime>" + payTime + "</merOrderTime>"
							+ "<merTranTime>" + merTranTime + "</merTranTime>"
						+ "</order>"
						+ "<merchant>"
							+ "<merID>" + merID + "</merID>"
						+ "</merchant>"
						+ "<refund>"
							+ "<refundAction>" + refundType + "</refundAction>"
							+ "<refundAmt>" + refund.get("amount") + "</refundAmt>"
							+ "<refundActionMsg>" + refund.get("msg") + "</refundActionMsg>"
						+ "</refund>"
						+ "<security>"
							+ "<merSignMsg>" + merSignMsg + "</merSignMsg>"
							+ "<merCert>" + this.merCert + "</merCert>"
						+ "</security>"
					+ "</icbc_corporbank_credit_pay>");
		
		String xmlStr = buf.toString();
		//发送http的post请求
		String result = null;
		try {
			String args = URLEncoder.encode(xmlStr,"gbk");
//			args = URLEncoder.encode(xmlStr,"gbk");
			args = "CREDIT_PAY_DATA="+args;
			result = HttpsPost.ssl(MessageFormat.format(API_URL, this.domain), args);
			result = URLDecoder.decode(result,"gbk"); 
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException{
		String text = "CREDIT_PAY_DATA=%3C%3Fxml++version%3D%221.0%22+encoding%3D%22GBK%22+%3F%3E%3Cicbc_corporbank_credit_pay%3E%3CinterfaceName%3EICBC_CORPORBANK_CREDIT_MODIFY%3C%2FinterfaceName%3E%3CinterfaceVersion%3E1.0.0.2%3C%2FinterfaceVersion%3E%3Corder%3E%3CorderID%3EO1440829263611%3C%2ForderID%3E%3CmerOrderTime%3E20150828143637%3C%2FmerOrderTime%3E%3CmerTranTime%3E20150828150045%3C%2FmerTranTime%3E%3C%2Forder%3E%3Cmerchant%3E%3CmerID%3E1103EC13761206%3C%2FmerID%3E%3C%2Fmerchant%3E%3Crefund%3E%3CrefundAction%3E2%3C%2FrefundAction%3E%3CrefundAmt%3E99%3C%2FrefundAmt%3E%3CrefundActionMsg%3E%3C%2FrefundActionMsg%3E%3C%2Frefund%3E%3Csecurity%3E%3CmerSignMsg%3ElQSnIM7TUKuGWptXAcyclcIv1%2Bc4%2B7dWxXveV%2BiHHtMO0q1Pge4Sy1aFF4I7UAHenWGLsQsqE%2F0V%0D%0AcMbUM0TZWQbyn%2BtjCjBnzH2vUAXzX0MZKDMhqgAsm5kbAB1%2FOhl%2FMFhY0qFGk6J7lZ8K2JyFKlYG%0D%0Au4R9%2F9Uulyv2f60akwY%3D%3C%2FmerSignMsg%3E%3CmerCert%3EMIIDCjCCAfKgAwIBAgIKG5LKECVWAAJlXjANBgkqhkiG9w0BAQUFADA7MR8wHQYDVQQDExZJQ0JD%0D%0AIFRlc3QgQ29ycG9yYXRlIENBMRgwFgYDVQQKEw90ZXN0aWNiYy5jb20uY24wHhcNMTUwODIwMDY0%0D%0AOTU3WhcNMTYwODIwMDY0OTU3WjA%2BMRMwEQYDVQQDEwpoeTEuZS4xMTAzMQ0wCwYDVQQLEwQxMTAz%0D%0AMRgwFgYDVQQKEw90ZXN0aWNiYy5jb20uY24wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAK7%2F%0D%0A6cje37pY5Hnp%2BPinM3cZNjRQbKZx%2F6RQbTfT4CXwV0PeWbqurfaALYEcUfRPtEMeVM8CjgCTp3oo%0D%0A4W9BwvTxoak1YqzR1EXkJDWK3QCnCUVVUPQ06mZb2CKBUJq3FKImjPOphNwV4OPRxbO5q%2B3y1G7h%0D%0AVo6Jpdi136m0aBVJAgMBAAGjgZAwgY0wHwYDVR0jBBgwFoAURH23kCw3pNntbOKkh1dnCrXwTRQw%0D%0ASwYDVR0fBEQwQjBAoD6gPKQ6MDgxDjAMBgNVBAMTBWNybDMyMQwwCgYDVQQLEwNjcmwxGDAWBgNV%0D%0ABAoTD3Rlc3RpY2JjLmNvbS5jbjAdBgNVHQ4EFgQUX6HBLs0UG%2FAZSx7xcj5dcRFWO28wDQYJKoZI%0D%0AhvcNAQEFBQADggEBABoLM%2BLzqvF01xrNg1tAn9tv1CS7p90HFc9UteAggqqhWM23vb6vHJjjMu1N%0D%0AB0BMPyUhcMWCqxnskeJ4c0QwqwZK4js%2F8IFbenX5p9ZhgOMimDRT%2FR%2FWdTVOQcJDCwJjFWPvH93g%0D%0AVHhzgpxJk66jUbRSJs5cM8dxVxobmOm37Td6Dudd6nM6V7awOPZUu%2FeavRRU1Yp%2FK9voMhqdlQ5c%0D%0AFLIVMuaSNJ5eH8GWBAdW3l5s9DlIqU9asRvCfHDLxELY8JWbnhl38C9wp1m5y3fBlphlqrmLzGDw%0D%0AgmR9mLbkPFxkR3I%2BbddohPUrc%2B5Vg%2BbVJTdi2kg1JKKqTzblBaicf8U%3D%3C%2FmerCert%3E%3C%2Fsecurity%3E%3C%2Ficbc_corporbank_credit_pay%3E";
		text = URLDecoder.decode(text, "GBK");
		System.out.println(text);
//		Map<String,String> result = IcbcPay.me().parseResult("<?xml  version=\"1.0\" encoding=\"GBK\" standalone=\"no\" ?><icbc_corporbank_credit_pay><interfaceName>ICBC_CORPORBANK_CREDIT_PREPARE_PAY</interfaceName><interfaceVersion>1.0.0.2</interfaceVersion><order><orderID>O1439899284313</orderID><amount>100</amount><currType>001</currType><feeAmt>0</feeAmt><merTranTime>20150901200124</merTranTime><orderPeriod>24</orderPeriod><orderState></orderState><BankNotifyTime>20150901195901</BankNotifyTime></order><refund><refundFlag></refundFlag><refundAmtSum></refundAmtSum><appRefundAmt></appRefundAmt></refund><seller><sellerAcct>1103020209200500343</sellerAcct><sellerName>ÃºÌ¿</sellerName></seller><merchant><merID>1103EC13759210</merID><merAcctNum>1103020209200500343</merAcctNum><merAcctName>ÃºÌ¿</merAcctName></merchant><tran><requestType>0</requestType><requestResult></requestResult><ErrMsg>[41204]ÉÌ»§Ã»ÓÐ¿ªÍ¨ÐÅÓÃÖ§¸¶È¨ÏÞ</ErrMsg></tran><notify><buyerPhoneNum></buyerPhoneNum><sellerPhoneNum></sellerPhoneNum><merURL>http://fast.yfsoft.info/fast/admin/notify/payNotify</merURL></notify><security><bankSignMsg>VrGzOGi5b/CCsonc24LVhbqKudeO4wI4jLpWA30B7f3mwTK5QAxmbN0cP5g/nZoSyWmHPgn7Szk8HtQ8rAc5veRJbv4JvQLFJpjUpWtvjfXGpZYg+sbtsAD2gbTAUkX32Pp/DvrU3gqvLcVMY1yMrU5trXd1+U3f6BrEZdx7s3I=</bankSignMsg></security></icbc_corporbank_credit_pay>");
//		System.out.println(result);
//		Map<String,Object> refund = new HashMap<String,Object>();
//		refund.put("amount", "100"); //申请亏款的金额
//		refund.put("msg", "申请退款的原因"); //申请退款的原因
//		
//		String result = IcbcPay.me().applyRefund("O10101010101","201509081212111",refund);
//		Map<String,String> data = IcbcPay.me().parseResult(result);
//		String requestResult = data.get("requestResult");
//		/**
//		 * requestResult：
//空：支付错误
//0成功
//1失败
//2等待处理
//3待授权
//		 */
//		String refundFlag = data.get("refundFlag");
//		/**
//		 * refundFlag:
//空：退款状态
//0-未退款
//1-退款
//		 */
//		
//		//累计退款金额
//		String refundAmtSum = data.get("refundAmtSum");
//		
////		仲裁金额
//		String appRefundAmt = data.get("appRefundAmt");
		
		
	}
	
	/**
	 * 解析回调信息的结果
	 * 
	 * requestResult：
空：支付错误
0成功
1失败
2等待处理
3待授权


refundFlag:
空：退款状态
0-未退款
1-退款

refundAmtSum:
累计退款金额
appRefundAmt：
仲裁金额

	 * @param result
	 * @return
	 */
	public Map<String,String> parseResult(String result){
		JSONObject config = JSONObject.parseObject("{'orderID':'order/orderID',"
				+ "'interfaceName':'interfaceName',"
				+ "'merTranTime':'order/merTranTime',"
				+ "'sellerAcct':'seller/sellerAcct',"
				+ "'requestResult':'tran/requestResult',"
				+ "'error':'tran/ErrMsg',"
				+ "'amount':'order/amount',"
				+ "'refundFlag':'refund/refundFlag',"
				+ "'refundAmtSum':'refund/refundAmtSum',"
				+ "'appRefundAmt':'refund/appRefundAmt',"
				+ "'orderState':'order/orderState',"
				+ "'orderExpire':'order/orderExpire'}");
		Map<String,String> data = new HashMap<String,String>();
		try {
			Document doc = DocumentHelper.parseText(result);
			Element root = doc.getRootElement();
			Node node = null;
			for(String key :config.keySet()){
				String xpath = config.getString(key);
				node = root.selectSingleNode(xpath);
				if(node != null){
					data.put(key, node.getText());
				}else{
					data.put(key, "");
				}
				
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return data;
	}
	
	/**
	 * 申请退款
	 * @param ctrl
	 * @param order
	 */
 	public String applyRefund(String orderId,String payTime, Map<String,Object> refund){
		return refund(orderId,payTime,APPLY_REFUND,refund);
	}
	
	/**
	 * 确认退款
	 * @param ctrl
	 * @param order
	 */
	public String commitRefund(String orderId,String payTime, Map<String,Object> refund){
		return refund(orderId,payTime,COMMIT_REFUND,refund);
	}
	
	/**
	 * 撤销退款
	 * @param ctrl
	 * @param order
	 */
	public String rejectRefund(String orderId,String payTime, Map<String,Object> refund){
		return refund(orderId,payTime,REJECT_REFUND,refund);
	}
	
	public String delayOrder(String orderId,String payTime){
		String merTranTime = getNowTranTime();
		
		String BASE_SIGNSTR = "interfaceName=ICBC_CORPORBANK_CREDIT_DEFER_PAY&interfaceVersion=1.0.0.2"
				+ "&orderID={0}"   //订单号
				+ "&merOrderTime={1}"
				+ "&merTranTime={2}"
				+ "&merID={3}"
				+ "&deferOrderPeriod={4}"
				+ "&deferMsg={5}";
		String merSignMsg = MessageFormat.format(BASE_SIGNSTR,
				orderId,
				payTime,
				merTranTime,
				merID,
				orderPeriod,
				""//TODO:和工行确认是否是必须参与签名的字段
				);
		merSignMsg = base64enc(merSignMsg);
		StringBuffer buf = new StringBuffer();
		buf.append("<?xml  version=\"1.0\" encoding=\"GBK\" ?>"
					+ "<icbc_corporbank_credit_pay>"
						+ "<interfaceName>ICBC_CORPORBANK_CREDIT_DEFER_PAY</interfaceName>"
						+ "<interfaceVersion>1.0.0.2</interfaceVersion>"
						+ "<order>"
							+ "<orderID>" + orderId + "</orderID>"
							+ "<merOrderTime>" + payTime + "</merOrderTime>"
							+ "<merTranTime>" + merTranTime + "</merTranTime>"
							+ "<isChangeTime>0</isChangeTime>"
							+ "<newPaymentTime></newPaymentTime>"
						+ "</order>"
						+ "<merchant>"
							+ "<merID>" + merID + "</merID>"
						+ "</merchant>"
						+ "<defer>"
							+ "<deferOrderPeriod>" + orderPeriod + "</deferOrderPeriod>"
							+ "<deferMsg></deferMsg>"
						+ "</defer>"
						+ "<security>"
							+ "<merSignMsg>" + merSignMsg + "</merSignMsg>"
							+ "<merCert>" + this.merCert + "</merCert>"
						+ "</security>"
					+ "</icbc_corporbank_credit_pay>");
		
		String xmlStr = buf.toString();
		//发送http的post请求
		String result = null;
		try {
			String args = URLEncoder.encode(xmlStr,"gbk");
			args = "CREDIT_PAY_DATA="+args;
			result = HttpsPost.ssl(MessageFormat.format(API_URL, this.domain), args);
			result = URLDecoder.decode(result,"gbk"); 
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}


